// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, TextInput, InteractionManager, WebView } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import { Actions } from 'react-native-router-flux';

// antd 按需加载
import { Portal, Toast, List, Radio, Modal } from '@ant-design/react-native';
const Item = List.Item;
const Brief = Item.Brief;
const RadioItem = Radio.RadioItem;

// 引入 处理数据 所需文件
import { generateOrder, generateBehalfOrder, addOrder, pay } from './module/module.js'
import { getShopCartList } from '../ShoppingCart/module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, Title, HomeIndicator, IsPay } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, longitude, latitude, ScreenWidth, wxPay } from '../../util/utils.js'

class Pay extends Component {

  constructor(props) {
    super(props)
    this.state = {
      data: null,
      payType: null,
      payInfo: {
        isPay: false
      },
      orderNo: ''
    }
    this.generateOrder = generateOrder.bind(this)
    this.generateBehalfOrder = generateBehalfOrder.bind(this)
    this.addOrder = addOrder.bind(this)
    this.pay = pay.bind(this)
    this.getShopCartList = getShopCartList.bind(this)
  }

  componentDidMount() {

  }

  componentWillReceiveProps(nextProps) {
    console.log(nextProps)
    if (nextProps.isRefresh) {
      Actions.orderInfo({ id: this.state.orderNo.id })
    }
  }


  getQuantity() {
    const { order } = this.props
    let quantity = 0
    order.goodsList.map((item, index) => {
      quantity += item.quantity
    })
    return quantity
  }

  handleGenerateOrder() {
    const { confirmOrderPay, magazineOrder, bookOrder, order, orderPayType } = this.props
    const { payType } = this.state
    if (!payType) {
      Toast.fail('请选择支付方式', 1, null, false)
      return
    }
    // if (payType == 4) {
    //   Actions.payAtm()
    //   return
    // }
    this.loading = Toast.loading('支付中', 0, null, false)

    if (orderPayType && orderPayType == 'magazineOrder') {
      magazineOrder.payType = payType
      this.generateBehalfOrder(magazineOrder).then(res => {
        this.startPay(res.data.data.order.orderSn)
      }).catch(error => {
        Portal.remove(this.loading)
      })
    }
    if (orderPayType && orderPayType == 'bookOrder') {
      bookOrder.payType = payType
      this.addOrder(bookOrder).then(res => {
        this.startPay(res.data.data.order.orderSn)
      }).catch(error => {
        Portal.remove(this.loading)
      })
    }
    if (orderPayType && orderPayType == 'order') {
      order.goodsList.map((item) => {
        item.checked = 1
      })
      order.payType = payType
      this.generateOrder({
        ...order,
        useIntegration: 0,
        couponId: 0,
      }).then(res => {
        this.startPay(res.data.data.order)
      }).catch(error => {
        Portal.remove(this.loading)
      })
    }
  }

  startPay(order) {
    const { payType } = this.state
    this.pay({
      orderNo: order.orderSn,
      payMode: payType
    }).then(payRes => {
      console.log(payRes)
      Portal.remove(this.loading)
      // this.setState({
      //   html: res.data.data
      // })
      // Modal.alert('支付', '是否支付完成', [
      //   {
      //     text: '未完成',
      //     onPress: () => console.log('cancel'),
      //     style: 'cancel',
      //   },
      //   { text: '已支付', onPress: () => console.log('ok') },
      // ]);
      this.setState({
        isPay: true,
        orderNo: order
      }, () => {
        console.log(111)
        this.getShopCartList()
        if (payType == 4) {
          Actions.payAtm({
            orderNo: order
          })          
          return
        }
        Actions.payResults({ html: payRes.data.data })
      })

      // console.log(res.data.data)
    }).catch(error => {
      Portal.remove(this.loading)
    })
  }

  render() {
    const { confirmOrder, confirmOrderPay, magazineOrder, bookOrder, order, price, orderPayType,totalAmount,fee } = this.props
    const { payVisible, data, money, preferential, payType, html, payInfo } = this.state
    console.log(this)
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="支付"
          back={true}
        />
        <ScrollView
          style={[Style.content, {
            backgroundColor: '#e8e8ed'
          }]}
        >
          {/* 杂志 */}
          {orderPayType && orderPayType == 'magazineOrder' ? (
            <List>
              <Item extra={magazineOrder.productQuantity}>商品数量</Item>
              <Item extra={price}>商品总价</Item>
              {magazineOrder.delivery == 0 ? <Item extra={'0'}>自提</Item> : null}
              {magazineOrder.delivery == 1 ? <Item extra={'6'}>特快专递</Item> : null}
            </List>
          ) : null}

          {/* 书籍 */}
          {orderPayType && orderPayType == 'bookOrder' ? (
            <List>
              <Item extra={bookOrder.productQuantity}>商品数量</Item>
              <Item extra={price}>商品总价</Item>
              {bookOrder.delivery == 0 ? <Item extra={fee}>自提</Item> : null}
              {bookOrder.delivery == 1 ? <Item extra={fee}>特快专递</Item> : null}
            </List>
          ) : null}

          {/* 订单 */}
          {orderPayType && orderPayType == 'order' ? (
            <List>
              <Item extra={this.getQuantity()}>商品数量</Item>
              <Item extra={price}>商品总价</Item>
              {order.disModes == 1 ? <Item extra={fee}>自提</Item> : null}
              {order.disModes == 2 ? <Item extra={fee}>特快专递</Item> : null}
              <Item extra={totalAmount}>总计</Item>
            </List>
          ) : null}

          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 36, paddingHorizontal: 15 }}>支付方式</Text>
          <View
            style={{
              backgroundColor: '#fff',
              marginBottom: 10,
              borderTopColor: '#f4f4f4',
              borderTopWidth: .5,
            }}
          >
            <TouchableOpacity
              onPress={() => {
                this.setState({
                  payType: 3
                })
              }}
            >
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: 15,
                paddingVertical: 8,
                borderBottomColor: '#f4f4f4',
                borderBottomWidth: .5,
              }}>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 20, height: 20, }}>online-pay</Text>
                <View style={{ height: 20, justifyContent: 'center' }}>
                  {payType == 3 ? <Icon name="md-checkmark" size={14} color="#61676F"></Icon> : null}
                </View>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                this.setState({
                  payType: 4
                })
              }}
            >
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: 15,
                borderBottomColor: '#f4f4f4',
                borderBottomWidth: .5,
              }}>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 20, height: 20, }}>ATM转账</Text>
                <View style={{ height: 20, justifyContent: 'center' }}>
                  {payType == 4 ? <Icon name="md-checkmark" size={14} color="#61676F"></Icon> : null}
                </View>
              </View>
            </TouchableOpacity>
          </View>
          {/* 
          <List renderHeader={'支付方式'}>
            <RadioItem
              checked={payType == 3}
              onChange={event => {
                if (event.target.checked) {
                  this.setState({
                    payType: 3
                  })
                }
              }}
            >online-pay</RadioItem>
            <RadioItem
              checked={payType == 4}
              onChange={event => {
                if (event.target.checked) {
                  this.setState({
                    payType: 4
                  })
                }
              }}
            >ATM转账</RadioItem>
          </List> */}
          {/* {payType == 4 ? (
            <View style={{ padding: 15 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>请支付到以下账号：</Text>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>帐户名：LZ HANX SDN BHD Maybank 账号: 5141 696 2295 7</Text>
            </View>
          ) : null} */}
          {/* 
          <View style={{
            backgroundColor: '#fff',
            marginBottom: 10,
            borderRadius: 6,
            paddingVertical: 8,
          }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>商品数量</Text>
              <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{this.getQuantity()}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>商品总价</Text>
              <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{confirmOrder.calcAmount.totalAmount}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>特快专递</Text>
              <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>{confirmOrder.calcAmount.freightAmount}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>订单总价</Text>
              <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>{confirmOrder.calcAmount.payAmount}</Text>
            </View>
          </View> */}
        </ScrollView>
        <TouchableOpacity
          style={{
            paddingVertical: 14,
            paddingHorizontal: 20,
            backgroundColor: '#f23030',
            alignItems: 'center',
            justifyContent: 'center',
          }}
          onPress={() => this.handleGenerateOrder()}
        >
          <Text style={{ fontSize: 16, color: '#fff', lineHeight: 18, }}>确认支付</Text>
        </TouchableOpacity>
        <IsPay
          payInfo={payInfo}
          onCancel={() => {
            let payInfo = { ...payInfo }
            payInfo.isPay = false
            this.setState({
              payInfo
            })
          }}
        />
      </View>
    )
  }
}


export default connect(({ confirmOrder, confirmOrderPay }) => ({
  confirmOrder, confirmOrderPay,
}))(pureRender(Pay))
